<template>
  <div id="app">
    <MyHeader :addTodo="addTodo"/>
    <MyList 
      :todos="todos" 
      :checkTodo="checkTodo" 
      :deleteTodo="deleteTodo"
    />
    <MyFooter 
      :todos="todos" 
      :checkAllTodo="checkAllTodo" 
      :clearAll="clearAll"/>
    <Count/>
    <Cheng/>
    <ul>
      <li>
        <router-link to="/home">home</router-link>
      </li>
      <li>
        <router-link to="/about">about</router-link>
      </li>
    </ul>
    <router-view/>
  </div>
</template>

<script>
import MyHeader from './components/MyHeader.vue'
import MyList from './components/MyList.vue'
import MyFooter from './components/MyFooter.vue'
import Count from './components/Count.vue'
import Cheng from './components/Cheng.vue'
export default {
  name: 'App',
  data(){
    return {
      todos:JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  components: {
    MyHeader,
    MyList,
    MyFooter,
    Count,
    Cheng,
  },
  methods:{
    //添加代办事项
    addTodo(todo){
      this.todos.unshift(todo)
    },
    //勾选或者取消勾选
    checkTodo(id){
      this.todos.forEach((todo)=>{
        if(todo.id === id){todo.done = !todo.done}
      })
    },
    //删除对应的todo
    deleteTodo(id){
      this.todos = this.todos.filter((todo)=>{
        return todo.id !== id
      })
    },
    //全选或者取消全选
    checkAllTodo(done){
      this.todos.forEach((todo)=>{
        //console.log(todo.done)
        todo.done = done
      })
    },
    //清除所有已经完成的任务
    clearAll(){
      this.todos = this.todos.filter((todo)=>{
        return !todo.done
      })
    },
    //更新TODO
    updateTodo(id,title){
      this.todos.forEach((todo)=>{
        if(todo.id === id){todo.title = title}
      })
    }
  },
  watch:{
    todos:{
      deep:true,
      handler(value){
        localStorage.setItem('todos',JSON.stringify(value))
      }
    }
  },
  mounted(){
    this.$bus.$on('checkTodo',this.checkTodo)
    this.$bus.$on('deleteTodo',this.deleteTodo)
    this.$bus.$on('updateTodo',this.updateTodo)
  },
  beforeDestroy(){
    this.$bus.$off('checkTodo')
    this.$bus.$off('deleteTodo')
    this.$bus.$off('updateTodo')
  }
}
</script>
